//从服务器主动发送请求
//http.request(options[, callback])

const http = require('http')
const path = require('path')
const fs = require('fs')
const queryString = require("querystring")

//访问百度
let options = {
    hostname: 'www.baidu.com',
    port: 80
}

//访问本地 基于nodejs图书管理系统restful风格版 /books
options = {
    hostname: 'localhost',
    port: 3000,
    protocol: "http:",
    path: '/books'
}

options = {
    hostname: 'localhost',
    port: 3000,
    protocol: "http:",
    path: '/books/book',
    header: {
        'Content-Type': 'application/x-www/form-urlencoded'
    }
}

let data = queryString.stringify(({
    name: '萤窗小语',
    author: '刘墉',
    category: '文学',
    description: '一个个简单的小故事'
}))


let req = http.request(options, (res)=>{
    let info = ''
    res.on('data', (chunk)=>{
        info += chunk
        console.log(info)
    })
    res.on('end', ()=>{
        fs.writeFile(path.join(__dirname, 'local.json'), info, (err)=>{
            console.log("已经获取到图书信息")
        })
    })
})

req.write(data)

req.end()